package com.shanghaionstar.carmanage.service;

import android.content.Context;

import com.google.gson.Gson;
import com.onstar.cn.api.GprsPackageService;
import com.onstar.cn.api.UsersService;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;

import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.enumtype.PackageType;
import com.onstar.cn.payme.response.CreateOrderResponseType;
import com.shanghaionstar.carmanage.model.OnstarPayReq;
import com.shanghaionstar.carmanage.model.OrderStatus;
import com.shanghaionstar.carmanage.pay.alipay.AliPayCheckUtil;
import com.shanghaionstar.carmanage.pay.alipay.AliWebPayRepEntity;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.NetConnectUtil;

import rx.Observable;
import rx.functions.Func0;

/**
 * 流量套餐订单信息
 * Created by Yonglang Hong on 2016/7/27.
 */
public class FlowOrderInfoService extends BaseService {

    private Context context;

    public FlowOrderInfoService(Context context) {
        this.context = context;
    }

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public Object jsonToBean(String json) {
        return null;
    }

    public Observable<CreateOrderResponseType> getFlowPackageOrderInfo(final PackageType packageType, final String packageId) {
        return Observable.defer(new Func0<Observable<CreateOrderResponseType>>() {
            @Override
            public Observable<CreateOrderResponseType> call() {
                try {
                    return Observable.just(doGetFlowPackageOrderInfo(packageType,packageId));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<OnstarPayReq> genSignReq(final CreateOrderResponseType orderInfo, final String payType) {
        return Observable.defer(new Func0<Observable<OnstarPayReq>>() {
            @Override
            public Observable<OnstarPayReq> call() {
                try {
                    return Observable.just(genSignForOrder(orderInfo,payType));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<OrderStatus> queryOrderStatus(final String orderId) {
        return Observable.defer(new Func0<Observable<OrderStatus>>() {
            @Override
            public Observable<OrderStatus> call() {
                try {
                    return Observable.just(doQueryOrderStatus(orderId));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<AliWebPayRepEntity> payByAliWeb(final CreateOrderResponseType orderInfo) {
        return Observable.defer(new Func0<Observable<AliWebPayRepEntity>>() {
            @Override
            public Observable<AliWebPayRepEntity> call() {
                try {
                    return Observable.just(doPayByAliWeb(orderInfo));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    /**
     * 获取支付订单信息
     * @throws OnStarException
     */
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public CreateOrderResponseType doGetFlowPackageOrderInfo(PackageType packageType,String packageId) throws OnStarException {
        String vin = null;
        vin = ApplicationUtil.getInstance().getVin();
        String idpId = ApplicationUtil.getInstance().getIdpID();
        String accountId = ApplicationUtil.getInstance().getAccountId();

        String reqCreateOrder = "{\"packageInfo\":{\"packageId\":\"" + packageId + "\",\"packageType\":\""
                + packageType.toString() + "\"},\"subscriber\":{\"accounts\":{\"accountID\":\"" + accountId
                + "\",\"vehicles\":[{\"vin\":\"" + vin + "\"}]},\"idpID\":\"" + idpId + "\"}}";

        GprsPackageService service = new GprsPackageService(Constants.CURRENT_SERVER_URL,context);

        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity.setBody(reqCreateOrder);

        service.CreateOrder(requestEntity, idpId, accountId, vin, packageId, packageType);
        requestEntity =  HttpInjectUtils.injectHttp(getClass(), "doGetFlowPackageOrderInfo", requestEntity,PackageType.class,String.class);
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));

        return GsonHelper.fromJson(response,CreateOrderResponseType.class);
    }

    /**
     * 获取订单签名信息
     * @throws OnStarException
     */
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public OnstarPayReq genSignForOrder(CreateOrderResponseType orderInfo, String payType) throws OnStarException {
        String vin = null;
        vin = ApplicationUtil.getInstance().getVin();
        String idpId = ApplicationUtil.getInstance().getIdpID();
        String accountId = ApplicationUtil.getInstance().getAccountId();

//        String reqCreateOrder = "{\"packageInfo\":{\"packageId\":\"" + packageId + "\",\"packageType\":\""
//                + packageType.toString() + "\"},\"subscriber\":{\"accounts\":{\"accountID\":\"" + accountId
//                + "\",\"vehicles\":[{\"vin\":\"" + vin + "\"}]},\"idpID\":\"" + idpId + "\"}}";
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
//        payOrder
//        GprsPackageService service = new GprsPackageService(Constants.CURRENT_SERVER_URL);

        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity.setBody(new Gson().toJson(orderInfo));
        String orderId = orderInfo.getOrderId();
        service.payOrder(requestEntity,idpId,accountId,vin,payType,orderId);

        requestEntity =  HttpInjectUtils.injectHttp(getClass(), "genSignForOrder", requestEntity,CreateOrderResponseType.class,String.class);
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        return new Gson().fromJson(response,OnstarPayReq.class);
//        return JsonParseUtil.JsonToBean(PayReq.class,response);
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public OrderStatus doQueryOrderStatus(String orderId) throws OnStarException {
        String vin = null;

        vin = ApplicationUtil.getInstance().getVin();
        String accountId = ApplicationUtil.getInstance().getAccountId();
        String subsriberId = ApplicationUtil.getInstance().getSubscriberID();
        GprsPackageService service = new GprsPackageService(Constants.CURRENT_SERVER_URL,context);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);

        service.GetOrderbyId(requestEntity, subsriberId, accountId, vin, orderId);
        requestEntity =  HttpInjectUtils.injectHttp(getClass(), "doQueryOrderStatus", requestEntity,String.class);
        return GsonHelper.fromJson(NetConnectUtil.getResponse(getDatas(requestEntity)),OrderStatus.class);
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public AliWebPayRepEntity doPayByAliWeb(CreateOrderResponseType orderInfo) throws OnStarException {
        String vin = null;
        vin = ApplicationUtil.getInstance().getVin();
        String accountId = ApplicationUtil.getInstance().getAccountId();
        String subsriberId = ApplicationUtil.getInstance().getSubscriberID();

        GprsPackageService service = new GprsPackageService(Constants.CURRENT_SERVER_URL,context);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        final String subject = orderInfo.getPackageInfo().getPackageName();
        String total_fee = orderInfo.getPackageInfo().getActualPrice() + "";
        String callbackurl = "<script language='javascript'>window.opener=null;window.close();</script>";
        String reqCreateOrder = "{\"outTradeNo\": \"" + orderInfo.getOrderId() + "\", \"subject\": \"" + subject
                + "\", \"totalFee\": \"" + total_fee + "\",\"callBackUrl\": \"" + callbackurl + "\"}";
        requestEntity.setBody(reqCreateOrder);

        service.GetAlipayWapUrl(requestEntity, subsriberId, accountId, vin);
        requestEntity =  HttpInjectUtils.injectHttp(getClass(), "doPayByAliWeb", requestEntity,CreateOrderResponseType.class);

        return GsonHelper.fromJson(NetConnectUtil.getResponse(getDatas(requestEntity)),AliWebPayRepEntity.class);
    }


}